//
//  HomeViewController.swift
//  新浪微博-初建项目
//
//  Created by danny on 15/6/24.
//  Copyright © 2015年 DannyLiu. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeViewController: BaseViewController {
    /// 转场动画是否已经被展示出来
    var isPresented = false
    /// 表格绑定的模型数组
    var statusesList: [Status]? {
        didSet {
            
            // 刷新表格数据
            tableView.reloadData()
        }
        
    }
    /// 懒加载行高缓存池
    lazy var rowHeightCache = [Int: CGFloat]()
    
    // 内存警告时 清空缓存
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
        rowHeightCache.removeAll()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitView?.setupViewInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        // 先判断一番 如果没有登录在这个时候就可以返回了
        if !userlogon {
            return
        }
        // TODO: 以下都是要登录后才能调用的,需要在这加个是否登录的判断
        
        // 设置navBar
        setupNavBar()
        
        // 加载微博数据
        loadData()
        
        // 注册可重用cell(.self可以直接获得类)
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: "Cell")
        
        // 注意 在手动设置行高以后,下面这俩方法都不能再用了,否则会出问题
//        tableView.estimatedRowHeight = 200
//        tableView.rowHeight = UITableViewAutomaticDimension

        // 取消cell之间的分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        
    }
    
    private func loadData(){
        
        Status.loadStatus { (statuses, error) -> () in
            
            if error != nil {
                SVProgressHUD.showInfoWithStatus("傻逼网络")
                return
            }
            
            // 提示，后续会有下拉刷新，没有新微博的情况，不要报错!
            if statuses == nil {
                print("木有新的数据")
                return
            }
            // 现在可以进行赋值操作了
            self.statusesList = statuses
        }
    }
    
    
    // MARK: tableView的数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        // 如果 ?? 前面的值是nil, 就返回后面的值
        return self.statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        // 创建cell
        // 此方法是返回必选cell的,因此需要注册一个可重用cell,否则这句会崩(在viewDidLoad里注册)
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! StatusForwardCell
        
        // 进行赋值操作
        cell.status = statusesList![indexPath.row]
        
        return cell
    }
    
    ///  行高
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 获取数据对象
        let status = statusesList![indexPath.row]
        
        if rowHeightCache[status.id] != nil {
            
            
            print("从缓冲池加载行高")
            return rowHeightCache[status.id]!
        }
        
        // 获取cell
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as! StatusForwardCell
        
        let height = cell.rowHeight(status)
        
        
        // 把行高添加到缓冲池
        rowHeightCache[status.id] = height
        
        
        return height
    }
    
    
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 开启动画
        visitView?.startAnmiation()
    }

    
    private func setupNavBar(){
        
        // 先判断是否登陆了
//        if sharedUserAccount == nil {
//            
//            return
//        }
        
        // 1 设置左右的btn
        let leftBtn = UIButton()
        
        leftBtn.frame = CGRectMake(0, 0, 30, 30)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch"), forState: UIControlState.Normal)
        leftBtn.setImage(UIImage(named: "navigationbar_friendsearch_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: leftBtn)
        
        let rightBtn = UIButton()
        rightBtn.frame = CGRectMake(0, 0, 30, 30)
        rightBtn.setImage(UIImage(named: "navigationbar_pop"), forState: UIControlState.Normal)
        rightBtn.setImage(UIImage(named: "navigationbar_pop_highlighted"), forState: UIControlState.Highlighted)
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        // 2 设置中间的自定义btn
        let name = sharedUserAccount!.name!
        let midBtn = HomeTitleBtn()
        
        midBtn.frame = CGRectMake(0, 0, 120, 30)
        midBtn.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
        
        midBtn.titleLabel?.font = UIFont.systemFontOfSize(17)
//        midBtn.titleLabel!.text = name + " "
        midBtn.setTitle("  " + name + "  ", forState: UIControlState.Normal)
        midBtn.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Normal)
        
        navigationItem.titleView = midBtn
        
        
        midBtn.addTarget(self, action: "midBtnClicked", forControlEvents: UIControlEvents.TouchUpInside)
        
    }
    
    ///   中间按钮的点击方法
    func midBtnClicked(){
    
        let sb = UIStoryboard(name: "POPover", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("POPover")
        
        // 设置代理
        vc.transitioningDelegate = self
        
        // 设置转场的样式(这个是原来的底部的main视图不会被销毁的关键)
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        
        
        presentViewController(vc, animated: true, completion: nil)

    
    }
    
}

/*

protocol UIViewControllerTransitioningDelegate : NSObjectProtocol {

optional func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning?

optional func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning?

optional func interactionControllerForPresentation(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?

optional func interactionControllerForDismissal(animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning?

@available(iOS 8.0, *)
optional func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController?
}

*/

extension HomeViewController:UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate {
    
    // 返回负责转场的控制器的对象
    func presentationControllerForPresentedViewController(presented: UIViewController, presentingViewController presenting: UIViewController, sourceViewController source: UIViewController) -> UIPresentationController? {
        
        //    init(presentedViewController: UIViewController, presentingViewController: UIViewController)

        return PopoverController(presentedViewController: presented ,presentingViewController: presenting)

//        return PopoverController(presentedViewController: presented ,presentingViewController: presenting)
        
        
        
    }
    
    
    //  转场动画展现出新的视图, 返回值为负责 提供 modal 动画 的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = true
        return self
    }
    
    
    //  动画效果销毁被展现出的新的视图, 返回值为提供dismissed的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    /*
    
    // This is used for percent driven interactive transitions, as well as for container controllers that have companion animations that might need to
    // synchronize with the main animation.
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval
    // This method can only  be a nop if the transition is interactive and not a percentDriven interactive transition.
    func animateTransition(transitionContext: UIViewControllerContextTransitioning)
    */
    
    // 设置动画时长
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 2.0
    }
    
    
    ///  转场动画实现函数,一旦实现此函数,所有的系统的转场动画效果失效
    ///
    ///  :param: transitionContext 转场上下文,提供了转场动画所需要的参数
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let fromVc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)
        let toVc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)
        
        print(fromVc)
        
        print(toVc)
        
        if isPresented {
         
        
            let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
            
            transitionContext.containerView()?.addSubview(toView)
            // 动画实现
            toView.transform = CGAffineTransformMakeScale(1.0, 0)
            toView.layer.anchorPoint = CGPointMake(0.5, 0)
            
            
            UIView.animateWithDuration(2.0, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 8, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in
                toView.transform = CGAffineTransformMakeScale(1.0, 1.0)
                
                }) { (_) -> Void in
                    transitionContext.completeTransition(true)
                    return
            }
        }else{
        
            let fromView = transitionContext.viewForKey(UITransitionContextFromViewKey)!
            
            fromView.removeFromSuperview()
            
            // 动画结束(这个必须写,否则ui会卡住,一直以为还在进行动画)
            transitionContext.completeTransition(true)
        }
    }
    
}










